import argparse
from typing import Any, Optional


class _GlobalConfig:
    """全局配置单例类"""

    _instance = None
    _config = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def initialize(self, config_path: Optional[str] = None):
        """初始化配置

        Args:
            config_path: 配置文件路径，如果为None则从命令行参数获取
        """
        if self._config is None:
            if config_path is None:
                parser = argparse.ArgumentParser(description="媒体信息处理服务")
                parser.add_argument("--config", "-c", type=str, help="配置文件路径")
                args = parser.parse_args()
                config_path = args.config

            self._config_path = config_path  # 保存配置路径
            from configs.config import Config

            self._config = Config(config_path) if config_path is not None else Config()
            
    def reload(self):
        """重新加载配置"""
        try:
            if self._config_path:
                from configs.config import Config
                self._config = Config(self._config_path)
                return True
            elif self._config is not None:
                # 如果之前没有保存路径，但已有配置对象，尝试重新初始化
                self.initialize()
                return True
            else:
                # 如果从未初始化过，先初始化
                self.initialize()
                return True
        except Exception:
            import traceback
            traceback.print_exc()
            return False


    def _ensure_initialized(self):
        """确保配置已初始化"""
        if self._config is None:
            self.initialize()

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项

        Args:
            key: 配置键，支持点分隔符如 'logging.level'
            default: 默认值

        Returns:
            配置值或默认值
        """
        self._ensure_initialized()
        return self._config.get(key, default) if self._config is not None else default

    @property
    def raw_config(self) -> Any:
        """安全获取原始配置对象

        Returns:
            配置对象，如果未初始化则返回None
        """
        self._ensure_initialized()
        return self._config


# 创建全局单例实例
global_config = _GlobalConfig()


# 初始化日志配置
def init_logging():
    """初始化日志配置"""
    logger_config = {
        "level": global_config.get("logging.level", "INFO"),
        "format": global_config.get(
            "logging.format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        ),
    }
    from utils.logger_config import LoggerConfig

    LoggerConfig(**logger_config)
